import { useRouter } from 'vue-router';
import type { RouteLocationRaw } from 'vue-router';
import type { RouteKey } from '@elegant-router/types';
import { router as globalRouter } from '@/router';

/**
 * 路由跳转相关 hooks
 *
 * useRouterPush：提供 push、back、通过路由 key 跳转等常用方法 支持 setup 内外调用
 */
export function useRouterPush(inSetup = true) {
  const router = inSetup ? useRouter() : globalRouter;
  const route = globalRouter.currentRoute;

  const routerPush = router.push; // 路由前进
  const routerBack = router.back; // 路由后退

  /**
   * 通过路由 key 跳转
   *
   * @param key 路由 key
   * @param options 跳转参数
   */
  async function routerPushByKey(key: RouteKey, options?: App.Global.RouterPushOptions) {
    const { query, params } = options || {};
    const routeLocation: RouteLocationRaw = {
      name: key
    };
    if (Object.keys(query || {}).length) {
      routeLocation.query = query;
    }
    if (Object.keys(params || {}).length) {
      routeLocation.params = params;
    }
    return routerPush(routeLocation);
  }

  /** 通过路由 key 并带 meta.query 跳转 */
  function routerPushByKeyWithMetaQuery(key: RouteKey) {
    const allRoutes = router.getRoutes();
    const meta = allRoutes.find(item => item.name === key)?.meta || null;
    const query: Record<string, string> = {};
    meta?.query?.forEach(item => {
      query[item.key] = item.value;
    });
    return routerPushByKey(key, { query });
  }

  /** 跳转到首页 */
  async function toHome() {
    return routerPushByKey('root');
  }

  /**
   * 跳转到登录页
   *
   * @param loginModule 登录方式
   * @param redirectUrl 跳转后重定向的地址
   */
  async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
    const module = loginModule || 'pwd-login';
    const options: App.Global.RouterPushOptions = {
      params: {
        module
      }
    };
    const redirect = redirectUrl || route.value.fullPath;
    options.query = {
      redirect
    };
    return routerPushByKey('login', options);
  }

  /**
   * Toggle login module
   *
   * @param module
   */
  async function toggleLoginModule(module: UnionKey.LoginModule) {
    const query = route.value.query as Record<string, string>;

    return routerPushByKey('login', { query, params: { module } });
  }

  /**
   * Redirect from login
   *
   * @param [needRedirect=true] Whether to redirect after login. Default is `true`
   */
  async function redirectFromLogin(needRedirect = true) {
    const redirect = route.value.query?.redirect as string;

    if (needRedirect && redirect) {
      await routerPush(redirect);
    } else {
      await toHome();
    }
  }

  return {
    routerPush,
    routerBack,
    routerPushByKey,
    routerPushByKeyWithMetaQuery,
    toHome,
    toLogin,
    toggleLoginModule,
    redirectFromLogin
  };
}
